import 'package:dio/dio.dart';
import 'package:get/get.dart';

import '../../utils/toast.dart';
import 'dio_config.dart';

class SDioBaseConfig extends SDioConfig {

  @override
  BaseOptions getBaseOptions() {
    return BaseOptions(
        connectTimeout: const Duration(seconds: 30),
        receiveTimeout: const Duration(seconds: 30),
        baseUrl: 'https://cbec-studapi.gzport.net',
        contentType: 'application/json;charset=UTF-8',
        headers: getBaseHeaders()
    );
  }

  // 处理业务码
  @override
  Future onResponse(data, Map extra) async {
    // 后端返回逻辑错误，统一100
    if (data is Map) {
      if (data['code'].toString() != "200") {
        throw SDioException(100, data['message'] ?? '');
      }

      if (data.containsKey('data')) {
        return data['data'];
      } else {
        throw SDioException(100, 'there is no data in response' ?? '');
      }

    } else {
      return data;
    }
  }

  // 处理http状态码而非业务码
  @override
  void onError(DioException error, Map? extra) {
    int UNKNOW = 400;
    int NETWORK = 500;
    String networkHint = "networkError".tr;
    bool showError = true;

    // debugPrint('showError111: ${options.headers}');
    // debugPrint('showError111: ${options.extra}');

    if (extra != null) {
      if (extra.containsKey('showError')) {
        // debugPrint('showError: ${extra}');
        showError = extra['showError'];
      }
    }

    // 暂时不区分具体错误，提示网络错误
    if (showError) Toast.show("networkError".tr);

    switch(error.type) {
      case DioExceptionType.badResponse:
        throw SDioException(NETWORK, error.toString());

      default:
        throw SDioException(NETWORK, error.toString());

    }

  }

  Map<String, dynamic> getBaseHeaders() {
    // logW('getBaseHeaders 中 afId: ${Af().afId}');
    return {
      'lang': 'es',
    };
  }

}